import { IndexedDB } from './indexedDB';
import { LocalStorage } from './localStorage';
import type { BaseStorage, StorageOptions } from './types';

export { IndexedDB } from './indexedDB';
export { LocalStorage } from './localStorage';
export * from './types';

/**
 * 默认存储选项
 */
const DEFAULT_OPTIONS: Partial<StorageOptions> = {
  version: 1,
  defaultTTL: 0, // 默认永不过期
  cleanupInterval: 60 * 1000, // 默认1分钟清理一次过期数据
};

/**
 * 创建存储实例
 * @param options 存储选项
 * @returns 存储实例
 */
export function createStorage<T>(options: StorageOptions): BaseStorage<T> {
  // 合并默认选项
  const mergedOptions: StorageOptions = { ...DEFAULT_OPTIONS, ...options };

  // 优先使用 IndexedDB
  if (IndexedDB.isAvailable()) {
    try {
      return new IndexedDB<T>(mergedOptions);
    } catch (error) {
      console.warn('IndexedDB 初始化失败，降级使用 LocalStorage:', error);
    }
  }

  // 降级使用 LocalStorage
  if (LocalStorage.isAvailable()) {
    return new LocalStorage<T>(mergedOptions);
  }

  throw new Error('没有可用的存储方案');
}

/**
 * 删除IndexedDB数据库
 * @param namespace 命名空间
 */
export function deleteDatabase(namespace: string): Promise<void> {
  return IndexedDB.deleteDatabase(namespace);
}

/**
 * 检测浏览器存储功能支持情况
 */
export function detectStorageSupport(): {
  indexedDB: boolean;
  localStorage: boolean;
  sessionStorage: boolean;
} {
  return {
    indexedDB: IndexedDB.isAvailable(),
    localStorage: LocalStorage.isAvailable(),
    sessionStorage: (() => {
      try {
        const test = '__storage_test__';
        sessionStorage.setItem(test, test);
        sessionStorage.removeItem(test);
        return true;
      } catch {
        return false;
      }
    })(),
  };
}
